import { useRequest } from "ahooks"
import { Spin } from "antd"
import { queryTerminalStatus } from "./service"
import { history, styled } from '@umijs/max'
import { Chart } from '@antv/g2';
import { useEffect, useRef, useState } from "react";
import { Card } from "@/components/Card"
import { jump2target } from "@/utils/common";

const Content = styled.div`
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;

  .loading {
    width: 100% !important;
    height: 100% !important;
  }

  .tooltip {
    width: 100%;
    height: 60px;

    .row {
      width: 100%;
      height: 50%;
      display: flex;
      align-items: center;

      .item {
        flex: 1;
        display: flex;
        gap: 6px;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        .dot {
          width: 6px;
          height: 6px;
          border-radius: 6px;
        }

        .label {
          font-size: 12px;
          width: 36px;
          color: #888888;
        }

        .value {
          font-size: 12px;
          color: #222222;
          font-weight: bold;
          width: 40px;
        }
      }
    }
  }
`

const setChartConfig = (chart: Chart) => {
  chart
    .coordinate({ type: "theta", innerRadius: 0.7})

  chart
    .interval()
    .transform({ type: 'stackY' })
    .encode('y', 'value')
    .encode('color', 'color')
    .scale('color', { type: 'identity' });

  chart.render()
}

const setChartData = (chart: Chart, text: string, data: ChartValue[]) => {
  let total = 0
  data.forEach(item => total += (item.value as number))

  chart.clear()

  chart
    .coordinate({ type: "theta", innerRadius: 0.7})

  chart
    .interval()
    .transform({ type: 'stackY' })
    .encode('y', 'value')
    .encode('color', 'color')
    .scale('color', { type: 'identity' })
    .interaction('tooltip', {
      render: (e: any, {items}: any) => {
        let name = ''
        switch (items[0].color) {
          case '#E41019': name = '充电中'; break
          case '#22B573': name = '空闲'; break
          case '#fdb900': name = '占用'; break
          case '#fa5b06': name = '故障'; break
          case '#919090': name = '离线'; break
          case '#c7c7c7': name = '其他'; break
        }
        return `<div style="display:flex;gap:10px;">
          <div style="color:${items[0].color}">${name}:</div>
          <div>${items[0].value}</div>
        </div>`
      }
    });

  chart.data(data)

  chart
    .text()
    .style('text', String(total))
    .style('x', '50%')
    .style('y', '45%')
    .style('fontSize', 40)
    .style('fontWeight', 'bold')
    .style('textAlign', 'center');

  chart
    .text()
    .style('text', text)
    .style('x', '50%')
    .style('y', '60%')
    .style('fontSize', 14)
    .style('fontWeight', 'bold')
    .style('textAlign', 'center');

  chart.render()
}

const TerminalStatusCard: React.FC = () => {
  const directChart = useRef<Chart>()
  const exchangeChart = useRef<Chart>()
  const [toggle, setToggle] = useState<Record<string, boolean>>({
    acChargeNum: true,  acFreeNum: true, acOccupyNum: true,
    acErrorNum: true, acOffLineNum: true, acOtherNum: true,
    dcChargeNum: true,  dcFreeNum: true, dcOccupyNum: true,
    dcErrorNum: true, dcOffLineNum: true, dcOtherNum: true,
  })
  const { data, loading } = useRequest(queryTerminalStatus, {
    onSuccess: data => {
      setChartData(directChart.current!, '直流终端数', [
        {label: '充电中', value: data.data.acChargeNum, color: '#E41019'},
        {label: '空闲', value: data.data.acFreeNum, color: '#22B573'},
        {label: '占用', value: data.data.acOccupyNum, color: '#fdb900'},
        {label: '故障', value: data.data.acErrorNum, color: '#fa5b06'},
        {label: '离线', value: data.data.acOffLineNum, color: '#919090'},
        {label: '其他', value: data.data.acOtherNum, color: '#c7c7c7'},
      ])
      setChartData(exchangeChart.current!, '交流终端数', [
        {label: '充电中', value: data.data.dcChargeNum, color: '#E41019'},
        {label: '空闲', value: data.data.dcFreeNum, color: '#22B573'},
        {label: '占用', value: data.data.dcOccupyNum, color: '#fdb900'},
        {label: '故障', value: data.data.dcErrorNum, color: '#fa5b06'},
        {label: '离线', value: data.data.dcOffLineNum, color: '#919090'},
        {label: '其他', value: data.data.dcOtherNum, color: '#c7c7c7'},
      ])
    }
  })

  const toggleData = (key: string) => {
    toggle[key] = !toggle[key]
    setToggle({...toggle})
    if (!data?.data) return
    setChartData(directChart.current!, '直流终端数', [
      {label: '充电中', value: data.data.acChargeNum, color: '#E41019', key: 'acChargeNum'},
      {label: '空闲', value: data.data.acFreeNum, color: '#22B573', key: 'acFreeNum'},
      {label: '占用', value: data.data.acOccupyNum, color: '#fdb900', key: 'acOccupyNum'},
      {label: '故障', value: data.data.acErrorNum, color: '#fa5b06', key: 'acErrorNum'},
      {label: '离线', value: data.data.acOffLineNum, color: '#919090', key: 'acOffLineNum'},
      {label: '其他', value: data.data.acOtherNum, color: '#c7c7c7', key: 'acOtherNum'},
    ].filter(item => toggle[item.key]))
    setChartData(exchangeChart.current!, '交流终端数', [
      {label: '充电中', value: data.data.dcChargeNum, color: '#E41019', key: 'dcChargeNum'},
      {label: '空闲', value: data.data.dcFreeNum, color: '#22B573', key: 'dcFreeNum'},
      {label: '占用', value: data.data.dcOccupyNum, color: '#fdb900', key: 'dcOccupyNum'},
      {label: '故障', value: data.data.dcErrorNum, color: '#fa5b06', key: 'dcErrorNum'},
      {label: '离线', value: data.data.dcOffLineNum, color: '#919090', key: 'dcOffLineNum'},
      {label: '其他', value: data.data.dcOtherNum, color: '#c7c7c7', key: 'dcOtherNum'},
    ].filter(item => toggle[item.key]))
  }

  const jump2warning = () => {
    jump2target(`/fault/stubFault`)
  }
  
  useEffect(() => {
    directChart.current = new Chart({container: 'directDiv', autoFit: true, height: 284})
    setChartConfig(directChart.current)

    exchangeChart.current = new Chart({container: 'exchangeDiv', autoFit: true, height: 284})
    setChartConfig(exchangeChart.current)
  }, []);

  return <Card
    header={<span style={{lineHeight: '32px'}}>终端状态</span>}
    extra={<a onClick={jump2warning}>警告管理</a>}
  >
    <Spin spinning={loading}>
      <Content>
        <div style={{width: '100%', height: 344}}>
          <div id='directDiv'></div>
          <div className="tooltip">
            <div className="row">
              <div className="item" onClick={() => toggleData('acChargeNum')}>
                <div className="dot" style={{backgroundColor: '#E41019'}}></div>
                <div className="label">充电中</div>
                <div className="value">{data?.data.acChargeNum || 0}</div>
              </div>
              <div className="item" onClick={() => toggleData('acFreeNum')}>
                <div className="dot" style={{backgroundColor: '#22B573'}}></div>
                <div className="label">空闲</div>
                <div className="value">{data?.data.acFreeNum || 0}</div>
              </div>
              <div className="item" onClick={() => toggleData('acOccupyNum')}>
                <div className="dot" style={{backgroundColor: '#fdb900'}}></div>
                <div className="label">占用</div>
                <div className="value">{data?.data.acOccupyNum || 0}</div>
              </div>
            </div>
            <div className="row">
              <div className="item" onClick={() => toggleData('acErrorNum')}>
                <div className="dot" style={{backgroundColor: '#fa5b06'}}></div>
                <div className="label">故障</div>
                <div className="value">{data?.data.acErrorNum || 0}</div>
              </div>
              <div className="item" onClick={() => toggleData('acOffLineNum')}>
                <div className="dot" style={{backgroundColor: '#919090'}}></div>
                <div className="label">离线</div>
                <div className="value">{data?.data.acOffLineNum || 0}</div>
              </div>
              <div className="item" onClick={() => toggleData('acOtherNum')}>
                <div className="dot" style={{backgroundColor: '#c7c7c7'}}></div>
                <div className="label">其他</div>
                <div className="value">{data?.data.acOtherNum || 0}</div>
              </div>
            </div>
          </div>
        </div>
        <div style={{width: '100%', height: 344}}>
          <div id='exchangeDiv'></div>
          <div className="tooltip">
            <div className="row">
              <div className="item" onClick={() => toggleData('dcChargeNum')}>
                <div className="dot" style={{backgroundColor: '#E41019'}}></div>
                <div className="label">充电中</div>
                <div className="value">{data?.data.dcChargeNum || 0}</div>
              </div>
              <div className="item" onClick={() => toggleData('dcFreeNum')}>
                <div className="dot" style={{backgroundColor: '#22B573'}}></div>
                <div className="label">空闲</div>
                <div className="value">{data?.data.dcFreeNum || 0}</div>
              </div>
              <div className="item" onClick={() => toggleData('dcOccupyNum')}>
                <div className="dot" style={{backgroundColor: '#fdb900'}}></div>
                <div className="label">占用</div>
                <div className="value">{data?.data.dcOccupyNum || 0}</div>
              </div>
            </div>
            <div className="row">
              <div className="item" onClick={() => toggleData('dcErrorNum')}>
                <div className="dot" style={{backgroundColor: '#fa5b06'}}></div>
                <div className="label">故障</div>
                <div className="value">{data?.data.dcErrorNum || 0}</div>
              </div>
              <div className="item" onClick={() => toggleData('dcOffLineNum')}>
                <div className="dot" style={{backgroundColor: '#919090'}}></div>
                <div className="label">离线</div>
                <div className="value">{data?.data.dcOffLineNum || 0}</div>
              </div>
              <div className="item" onClick={() => toggleData('dcOtherNum')}>
                <div className="dot" style={{backgroundColor: '#c7c7c7'}}></div>
                <div className="label">其他</div>
                <div className="value">{data?.data.dcOtherNum || 0}</div>
              </div>
            </div>
          </div>
        </div>
      </Content>
    </Spin>
  </Card>
}

export default TerminalStatusCard